package com.loopy.batch_;

import com.loopy.utils.jdbcUtils;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Batch_ {
    @Test
    public void noBatch(){
        Connection connection = jdbcUtils.getConnection();
        String sql="insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            System.out.println("开始执行");
            long start = System.currentTimeMillis();
            for(int i=0;i<5000;i++){
                preparedStatement.setString(1,"jack"+i);
                preparedStatement.setString(2,"666");
                preparedStatement.executeUpdate();
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时"+(end-start));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtils.close(null,preparedStatement,connection);
        }
    }

    @Test
    public void useBatch(){
        Connection connection = jdbcUtils.getConnection();
        String sql="insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            System.out.println("开始执行");
            long start = System.currentTimeMillis();
            for(int i=0;i<5000;i++){
                preparedStatement.setString(1,"jack"+i);
                preparedStatement.setString(2,"666");
                //将sql语句加到批处理中
                preparedStatement.addBatch();
                if((i+1)%1000==0){
                   preparedStatement.executeBatch();
                   preparedStatement.clearBatch();
                }
            }

            long end = System.currentTimeMillis();
            System.out.println("耗时"+(end-start));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtils.close(null,preparedStatement,connection);
        }
    }
}
